#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PyQt4 import QtCore, QtGui
from Ui_dialog_edit_AE import *
from libASFX import *

import dialog_new_relation
reload( dialog_new_relation)
from dialog_new_relation import dialog_new_relation

import dialog_add_new_attribute
reload( dialog_add_new_attribute)
from dialog_add_new_attribute import dialog_add_new_attribute

    
class relation_request():
    def __init__(self, child, relation):
        self.child = child
        #self.parent = parent
        self.relation = relation

class dialog_Edit_EA(QtGui.QDialog, Ui_Dialog_edit_AE):
    def __init__(self,parent,AE, relation_type_id,libmyCF):
        super(dialog_Edit_EA,self).__init__(parent)
        
        self.setupUi(self)
        self.parent=parent
        self.AE = AE
        #print self.AE.name, self.AE.source, self.AE.curator
        self.relation_type_id = relation_type_id
        self.libmyCF = libmyCF
        
        self.initialization_table_relations()   
        self.initialization_table_attributs()
        self.initialization_edit_dialog_buttons()
        
        #initialization of UI
        self.lineEdit_AE_id.setText(str(self.AE.AE_id))
        self.lineEdit_Name.setText(QtCore.QString.fromUtf8(self.AE.name))
        if self.AE.definition:
            self.textEdit_definition.setText(QtCore.QString.fromUtf8(self.AE.definition))
        if self.AE.source:
            self.lineEdit_source.setText(QtCore.QString.fromUtf8(self.AE.source))
        if self.AE.curator:
            self.lineEdit_curator.setText(QtCore.QString.fromUtf8(self.AE.curator))
        
        #Connections
        self.connect(self.lineEdit_Name, QtCore.SIGNAL("textChanged (const QString&)"),self.editors_changed)
        self.connect(self.textEdit_definition, QtCore.SIGNAL("textChanged ()"),self.editors_changed)
        self.connect(self.lineEdit_source, QtCore.SIGNAL("textChanged (const QString&)"),self.editors_changed)
        self.connect(self.lineEdit_curator, QtCore.SIGNAL("textChanged (const QString&)"),self.editors_changed)
        
        self.connect(self.pushButton_Update, QtCore.SIGNAL("clicked()"),self.update_AE)
        

    def initialization_table_relations(self):  
        
        self.relations_current = []
        self.relations_original = []
                
        liste_relations = self.AE.get_l_relations()
                        
        for relation in liste_relations :
            
            relation_id = relation.relation_id
            child = relation.getChildAE()
            parent = relation.getParentAE()
            relation_type = relation.relation_type_id
            
            #Create 2 lists of relations, the current one will be edited every time an AE is added or deleted
            #At the end the 2 lists will be compared to know which relation have to deleted and those which have to be created
            self.relations_current.append(relation)
            self.relations_original.append(relation)
            
            child_name = child.name
            parent_name = parent.name
            relation_name = relation.getName()
            
            child = QtGui.QTableWidgetItem (child_name, 0)
            relation_type = QtGui.QTableWidgetItem (relation_name , 0)
            parent = QtGui.QTableWidgetItem (parent_name , 0) 
            
            # Find the position for the insertion of the row.
            position = self.tableWidget_relations.rowCount()
            # Creation of an empty row at the good position.
            self.tableWidget_relations.insertRow(position)
            # Insert item in the new row.
            self.tableWidget_relations.setItem(position, 0, child)
            self.tableWidget_relations.setItem(position, 2, parent)
            self.tableWidget_relations.setItem(position, 1, relation_type)
            
        # Resize of the tableWidget_relation's columns.    
        self.tableWidget_relations.resizeColumnsToContents()
        width = self.tableWidget_relations.columnWidth(0)+self.tableWidget_relations.columnWidth(1)+self.tableWidget_relations.columnWidth(2)
        if width < 543 : #width of the table widget 
            self.tableWidget_relations.horizontalHeader().setStretchLastSection(True)


    def initialization_table_attributs(self):
        
        self.attributes_current = []
        self.attributes_original = []
        
        liste_attributes = self.AE.getAttributes()
        
        i=0
        self.tableWidget_attributes.setRowCount(len(liste_attributes))
        
        for attribute in  liste_attributes:         
            
            ##Show attributes
            item = QtGui.QTableWidgetItem(QtCore.QString.fromUtf8(str(attribute.getName())),0)
            self.tableWidget_attributes.setItem(i,0,item)
            item = QtGui.QTableWidgetItem(QtCore.QString.fromUtf8(str(attribute.getType())),0)
            self.tableWidget_attributes.setItem(i,1,item)
            item = QtGui.QTableWidgetItem(QtCore.QString.fromUtf8(str(attribute.value)),0)
            self.tableWidget_attributes.setItem(i,2,item)
            item = QtGui.QTableWidgetItem(QtCore.QString.fromUtf8(str(attribute.getAE().name)),0)
            self.tableWidget_attributes.setItem(i,3,item)
            i=i+1


            self.attributes_current.append(attribute)
            self.attributes_original.append(attribute)          
            
        # Resize of the tableWidget_attributes's columns.    
        self.tableWidget_attributes.resizeColumnsToContents()
        width = self.tableWidget_attributes.columnWidth(0)+self.tableWidget_attributes.columnWidth(1)+self.tableWidget_attributes.columnWidth(2)+self.tableWidget_attributes.columnWidth(3)
        if width < 543 : #width of the table widget 
            self.tableWidget_attributes.horizontalHeader().setStretchLastSection(True)
    
    def initialization_edit_dialog_buttons(self) :
        
        if self.libmyCF.connector.access_mode == "read" or self.libmyCF.ontology.translation != "English translation" :
            self.pushButton_Update.setEnabled(False)
            self.lineEdit_Name.setReadOnly(True)
            self.textEdit_definition.setReadOnly(True)
            self.lineEdit_source.setReadOnly(True)
            self.lineEdit_curator.setReadOnly(True)
            self.pushButton_delete_relation.setEnabled(False)
            self.pushButton_add_child.setEnabled(False)
            self.pushButton_add_parent.setEnabled(False)
            self.pushButton_delete_attribute.setEnabled(False)
            self.pushButton_add_attribute.setEnabled(False)
            self.pushButton_edit_value.setEnabled(False)
            
            
    @QtCore.pyqtSignature("bool")
    def on_action_pushButton_Update_triggered(self):
        self.lineEdit_Name.setReadOnly(False)

    def editors_changed(self) :
        if str(self.lineEdit_Name.text()) <> str(self.AE.name) or self.textEdit_definition.document().toPlainText() <> QtCore.QString.fromUtf8(self.AE.definition) or str(self.lineEdit_source.text()) <> str(self.AE.source) or str(self.lineEdit_curator.text()) <> str(self.AE.curator):
           self.pushButton_Update.setEnabled(True)
        else:
            self.pushButton_Update.setEnabled(False)    

    
    def update_AE(self):
        new_name = unicode(self.lineEdit_Name.text()).encode('utf-8')
        new_name = new_name.capitalize()
        self.lineEdit_Name.setText(QtCore.QString(new_name))
        for ae in self.libmyCF.ontology.all_AEs.values() :
            if ae.name == new_name and ae.AE_id != self.AE.AE_id :
                QtGui.QMessageBox.warning(self, "myCF update","An AE with the name \'%s\' already exists.\nPlease choose an other name." % new_name)
                return
        
        name = unicode(self.lineEdit_Name.text()).encode('utf-8')
        definition = unicode(self.textEdit_definition.document().toPlainText()).encode('utf-8')
        source = unicode(self.lineEdit_source.text()).encode('utf-8')
        curator = unicode(self.lineEdit_curator.text()).encode('utf-8')
        
        sql = self.AE.update( name, definition, source, curator)
        if sql == True:
            QtGui.QMessageBox.information(self, "update successful",unicode("Database has been updated correctly."))
            QtGui.QDialog.accept(self) #à supprimer, mais modifier le guimycf pour qu'il mette  à jour le nom même si le dialogue edit n'a pas été "exécuté" (i.e validé)
        else:
            QtGui.QMessageBox.warning(self,"Database Error", unicode(sql))
    
   
    @QtCore.pyqtSignature("bool")
    def on_pushButton_delete_relation_clicked(self):        
        # return the set of selected items and True, if items are selected
        select = self.tableWidget_relations.selectionModel().selectedRows()
        
        if not select:
            QtGui.QMessageBox.information(self,"myCF information","You must select a relation to delete")
        else:
            # number of the selected row.
            row = select[0].row()
            
            #make sure that there is always at least one relation in the list, else the tree will lose sight of the AE
            if len(self.relations_current) == 1 :
                QtGui.QMessageBox.warning(self,"myCF Error","You can not delete all relations. Else the AE will not appear in the tree anymore. You might want to simply delete it")
                return #exit the function without deleting the relation
            
            
            # Remove out the list of relations
            for relation in self.relations_current :
                name_child = self.libmyCF.ontology.all_AEs[relation.child].name
                name_parent = self.libmyCF.ontology.all_AEs[relation.parent].name
                relation_name = self.libmyCF.ontology.all_relations_type[relation.relation_type_id].name
                
                same_name_child = (name_child == self.tableWidget_relations.item(row, 0).text())
                same_name_parent = (name_parent == self.tableWidget_relations.item(row, 2).text())
                same_relation_name = (relation_name == self.tableWidget_relations.item(row, 1).text())
                
                if same_name_child and same_name_parent and same_relation_name :
                    
                    #make sure that the other AE implicated in the relation with the current AE has always at least one relation in its list of relation
                    if not len(self.libmyCF.ontology.all_AEs[relation.child].get_l_relations()) > 1 :
                        QtGui.QMessageBox.warning(self,"myCF Error","You try to delete a relation with an AE which is implicated in no other relation.\nIt will not apper in the tree anymore.\nYou might want to simply delete this AE")
                        return #exit the function without deleting the relation

                    #delete the relation from list of relations
                    self.relations_current.remove(relation)
                    break
                       
            # Remove the relation from the table
            self.tableWidget_relations.removeRow(row)

    
    @QtCore.pyqtSignature("bool")
    def on_pushButton_add_child_clicked(self):
        """create new relation with an existing EA using the current EA as parent"""
        self.add_relation("child")
    
    @QtCore.pyqtSignature("bool")
    def on_pushButton_add_parent_clicked(self):
        """create new relation with an existing EA using the current EA as parent"""
        self.add_relation("parent")
        
    def add_relation(self,option):
        
        if option == "child":
            new_rel_dia = dialog_new_relation(self,self.AE, self.relation_type_id, self.libmyCF,0)
        if option == "parent": 
            new_rel_dia = dialog_new_relation(self,self.AE, self.relation_type_id, self.libmyCF,1)

        # ".exec_" :
        # if accept => true,
        # if reject => false.
        if new_rel_dia.exec_():      
            new_rel = Relation(self.libmyCF, 0, new_rel_dia.child[1], new_rel_dia.parent[1], new_rel_dia.selected_relation)     
            
            #verify that the same relation has not just been added in the list
            for rel in self.relations_current :
                #if new_relation == relation : #does not work : the program compares the memory adresse and not the values
                if new_rel.child == rel.child and new_rel.parent == rel.parent and new_rel.relation_type_id == rel.relation_type_id:
                    QtGui.QMessageBox.warning(self, "myCF Error","You've just created the same relation.")
                    return
                            
            #add new relation to the list
            self.relations_current.append(new_rel)         
                                        
            # Maybe n = n - 1 after
            n = self.tableWidget_relations.rowCount()
            
            # Creation of the Item of the QTableWidget.
            child = QtGui.QTableWidgetItem (new_rel_dia.child[0] , 0)
            relation_type = QtGui.QTableWidgetItem (self.libmyCF.ontology.all_relations_type[new_rel_dia.selected_relation].name , 0)
            parent = QtGui.QTableWidgetItem (new_rel_dia.parent[0] , 0) 
            
            # Find the position for the insertion of the row.
            position = self.tableWidget_relations.rowCount()
            # Creation of an empty row at the good position.
            self.tableWidget_relations.insertRow(position)
            # Insert item in the new row.
            self.tableWidget_relations.setItem(position, 0, child)
            self.tableWidget_relations.setItem(position, 2, parent)
            self.tableWidget_relations.setItem(position, 1, relation_type)
            # Resize of the tableWidget_relation's columns.    
            self.tableWidget_relations.resizeColumnsToContents()
            
            width = self.tableWidget_relations.columnWidth(0)+self.tableWidget_relations.columnWidth(1)+self.tableWidget_relations.columnWidth(2)
            if width < 543 : #width of the table widget 
                self.tableWidget_relations.horizontalHeader().setStretchLastSection(True)

            
    @QtCore.pyqtSignature("bool")
    def on_pushButton_add_attribute_clicked(self):
        """create new attribute"""
        new_att_dia = dialog_add_new_attribute( self, self.libmyCF, None, None)
        
        if new_att_dia.exec_():
            
            # Look at "on_pushButton_add_relation_clicked" for more information.
            att_type = self.libmyCF.ontology.all_attributes_type[new_att_dia.selected_attribute_type_id]
            name = att_type.name
            type = att_type.type
            value = new_att_dia.selected_value
            inherited_from = self.AE.name
            
            item_name = QtGui.QTableWidgetItem (name , 0)
            item_Type = QtGui.QTableWidgetItem (type , 0)
            item_value = QtGui.QTableWidgetItem (value , 0)
            item_inherited_from = QtGui.QTableWidgetItem (inherited_from , 0)
            
            position = self.tableWidget_attributes.rowCount()
            
            self.tableWidget_attributes.insertRow(position)
            
            self.tableWidget_attributes.setItem(position, 0, item_name)
            self.tableWidget_attributes.setItem(position, 1, item_Type)
            self.tableWidget_attributes.setItem(position, 2, item_value)
            self.tableWidget_attributes.setItem(position, 3, item_inherited_from)
            
            #print self.tableWidget_attributes.item(0, 0).isSelected()
            
            #add atribute to the list attibutes_current
            #for attribute_type in self.ontology.all_attributes_type :
            #    if attribute_type.name == name:
            #        attribute_type_id = attribute_type.attribute_type_id
                
            new_att = Attribute(self.libmyCF, None, att_type.getId(), self.AE.AE_id, value)
            self.attributes_current.append(new_att)

            
            # Resize of the tableWidget_attributes's columns.    
            self.tableWidget_attributes.resizeColumnsToContents()
            width = self.tableWidget_attributes.columnWidth(0)+self.tableWidget_attributes.columnWidth(1)+self.tableWidget_attributes.columnWidth(2)+self.tableWidget_attributes.columnWidth(3)
            if width < 543 : #width of the table widget 
                self.tableWidget_attributes.horizontalHeader().setStretchLastSection(True) 

    @QtCore.pyqtSignature("bool")
    def on_pushButton_delete_attribute_clicked(self):        
        # return the set of selected items and True, if items are selected
        select = self.tableWidget_attributes.selectionModel().selectedRows()
        
        if not select:
            QtGui.QMessageBox.information(self,"myCF information","You must select an attribute to delete")
        else :
            # number of the selected row.
            row = select[0].row()
            
            # Remove out of the list of attributes
            for attribute in self.attributes_current :
                attribute_type_name  = attribute.getName()
                AE_name = attribute.getAE().name
                value = attribute.value
                
                same_att_type_name = (attribute_type_name == self.tableWidget_attributes.item(row, 0).text())
                same_value = (value == self.tableWidget_attributes.item(row, 2).text())
                same_AE_name = (AE_name == self.tableWidget_attributes.item(row, 3).text())
                
                if same_att_type_name and same_AE_name and same_value :
                    
                    #delete the matching attribute from list of attributes
                    self.attributes_current.remove(attribute)
                    # Remove the attribute from the table
                    self.tableWidget_attributes.removeRow(row)
                    break          

    
    @QtCore.pyqtSignature("bool")
    def on_pushButton_edit_value_clicked(self):
        """create new attribute"""
        select = self.tableWidget_attributes.selectionModel().selectedRows()
        
        if not select:
            QtGui.QMessageBox.information(self,"myCF information","You must select an attribute to edit")
            # number of the selected row.
        else :
            row = select[0].row()
            
            #Get the attribute_id of the selected attribute
            for attribute in self.attributes_current :
                attribute_type_name  = attribute.getName()
                AE_name = attribute.getAE().name
                value = attribute.value
                
                same_att_type_name = (attribute_type_name == self.tableWidget_attributes.item(row, 0).text())
                same_value = (value == self.tableWidget_attributes.item(row, 2).text())
                same_AE_name = (AE_name == self.tableWidget_attributes.item(row, 3).text())
                
                if same_att_type_name and same_AE_name and same_value :
                    
                    #retrieve the id of the matching attribute
                    attribute_id = attribute.attribute_id
                    old_attribute = attribute
                    break
                    #self.attributes_current.remove(attribute)

            #Retrieving the needed parameters for launching the attribute edit dialog and launching the attribute edit dialog
            attribute_type_name = self.tableWidget_attributes.item(row, 0).text()
            for attribute_type in self.libmyCF.ontology.all_attributes_type :
                if self.libmyCF.ontology.all_attributes_type[attribute_type].name == attribute_type_name :
                    attribute_type_id = attribute_type
                    break
            value = self.tableWidget_attributes.item(row, 2).text()
            edit_att_dia = dialog_add_new_attribute( self, self.libmyCF, attribute_type_id, value)
        
            if edit_att_dia.exec_():
                
                #print self.AE.AE_id
                #print old_attribute.AE_id
                
                if (self.AE.AE_id == old_attribute.AE_id) : # Attribut non hérité 
                
                    new_value = edit_att_dia.selected_value
                    #update item:
                    self.tableWidget_attributes.item(row, 2).setText(new_value)
                    #update database and ontology
                    #self.ontology.update_attribute(attribute_id,value) #Instead of updating the attribute, we delete it and create a new one
                    self.attributes_current.remove(old_attribute)
                    new_attribute = Attribute(self.libmyCF,old_attribute.attribute_id, old_attribute.attribute_type_id,old_attribute.AE_id, new_value)
                    self.attributes_current.append(new_attribute)
                
                else : # Attribut hérité 
                    
                    new_value = edit_att_dia.selected_value
                    #update item:
                    self.tableWidget_attributes.item(row, 2).setText(new_value)
                    self.tableWidget_attributes.item(row, 3).setText(self.AE.name)
                    #update database and ontology
                    #self.ontology.update_attribute(attribute_id,value) #Instead of updating the attribute, we delete it and create a new one
                    new_attribute = Attribute(self.libmyCF,old_attribute.attribute_id, old_attribute.attribute_type_id,self.AE.AE_id, new_value)
                    self.attributes_current.append(new_attribute)                                                            
                
                # Resize of the tableWidget_attributes's columns.    
                self.tableWidget_attributes.resizeColumnsToContents()
                width = self.tableWidget_attributes.columnWidth(0)+self.tableWidget_attributes.columnWidth(1)+self.tableWidget_attributes.columnWidth(2)+self.tableWidget_attributes.columnWidth(3)
                if width < 543 : #width of the table widget 
                    self.tableWidget_attributes.horizontalHeader().setStretchLastSection(True) 


    @QtCore.pyqtSignature("")
    def on_buttonBox_accepted(self):
        #create and delete relations
        if self.relations_current != self.relations_original :
            for relation in self.relations_current :
                if relation not in self.relations_original :
                    self.libmyCF.ontology.add_relation(relation.child,relation.parent,relation.relation_type_id)
        
            for relation in self.relations_original :
                if relation not in self.relations_current :
                    self.libmyCF.ontology.del_relation(relation.relation_id)
                    
        #create and delete attributes
        if self.attributes_current != self.attributes_original:
            for attribute in self.attributes_current :
                if attribute not in self.attributes_original :
                    self.libmyCF.ontology.add_attribute( attribute.attribute_type_id,attribute.AE_id,attribute.value)
        
            for attribute in self.attributes_original :
                if attribute not in self.attributes_current :
                    self.libmyCF.ontology.del_attribute(attribute.attribute_id)
        
                    
                
        QtGui.QDialog.accept(self)

  
    @QtCore.pyqtSignature("")
    def on_buttonBox_rejected(self):
        self.reject()

    def accept(self):
        QtGui.QDialog.accept(self)